package cn.liberg.coder.tool.template;

import cn.liberg.coder.tool.LibergToolContext;
import cn.liberg.coder.tool.LibergToolException;
import cn.liberg.coder.tool.core.Formats;
import cn.liberg.coder.tool.java.*;

import java.util.HashMap;
import java.util.Map;

public class TempDao {
	LibergToolContext context;
	String entityName;
	String selfName;
	String selfPath;
	JClass parser;
	JClassEntity entity;

	public TempDao(LibergToolContext ctx, JClassEntity entity) throws LibergToolException {
		context = ctx;
		this.entity = entity;
		entityName = entity.name;
		selfName = entityName + "Dao";
		selfPath = context.getDaoPath() + selfName + ".java";

		parser = new JClass(selfPath);
		if(!parser.loadedFromFile) {
			initTemplate();
		} else {
			updateTemplate();
		}
	}

	public void save() throws LibergToolException {
		parser.writeToFile(selfPath);
		String tip = "  created.";
		if(parser.loadedFromFile) {
			tip = "  updated.";
		}
		System.out.println("> " + context.getDaoPackage() + "." + selfName + tip);
	}

	private void initTemplate() {
		parser.mPackage = context.getDaoPackage();
		parser.name = selfName;
		updateTemplate();
	}

	private void updateTemplate() {
		String daoImplName = entityName + TempDaoImpl.SUFFIX;
		parser.defLine = "public class "+selfName+" extends "+daoImplName+" {";
		parser.addImport(context.getEntityPackage() + "." + entityName);
		parser.addImport(context.getDaoImplPackage() + "." + daoImplName);
		update();
	}

	private void update() {
		parser.addOrUpdateField(new JField("private static volatile "+selfName+" _instance;"));
		parser.addOrUpdateMethod(createSelfMethod());
	}

	private JMethod createSelfMethod() {
		JMethod jm = new JMethod("public static "+selfName+" self() {");
		jm.appendBodyLine("		if (_instance == null) {");
		jm.appendBodyLine("		    synchronized ("+selfName+".class) {");
		jm.appendBodyLine("                if (_instance == null) {");
		jm.appendBodyLine("                    _instance = new "+selfName+"();");
		jm.appendBodyLine("                }");
		jm.appendBodyLine("            }");
		jm.appendBodyLine("		}");
		jm.appendBodyLine("		return _instance;");
		return jm;
	}
}

